import {Config} from '../utils/config.js';
import {Token} from '../utils/token.js';

class Base{

  // 构造方法
  constructor() {
    this.baseRequestUrl = Config.baseUrl;
  }

  // 获取元素上绑定的值
  getDataSet(event, key) {
    return event.currentTarget.dataset[key];
  }

  // 封装发起请求的基类
  request(params, noRefresh) {
    var url = this.baseRequestUrl + params.url;
    var that = this;
    if (!params.type) {
      params.type = 'GET';
    }

    wx.request({
      url: url,
      data: params.data,
      method: params.type,
      header: {
        'content-type':'application/json',
        'token':wx.getStorageSync('token')
      },
      success: function(res){
        var code = res.statusCode.toString();

        if (code == 401) {
          if(!noRefresh){
            that._refecth(params);
          }else{
            params.eCallback && params.eCallback(res.data);
          }
        } else {
          params.sCallback && params.sCallback(res.data);
        }
      },
      fail: function(err){
        console.log(err);
      }
    })
  }

  /**
   * 刷新Token，重新发送请求
   * @param {*} params 
   */
  _refecth(params) {
    var token = new Token();
    token.getTokenFromServer((token) => {
      this.request(params, true);
    })
  }
}

export {Base}